package dao

import (
	"haiqiu-blog-go/models"
	"log"
)

func GetAllCategory() ([]models.Category, error) {
	rows, err := DB.Query("select * from blog_category")
	if err != nil {
		log.Println(err)
		return nil, err
	}
	var categorys []models.Category
	for rows.Next() {
		var category models.Category
		err := rows.Scan(&category.Cid, &category.Name, &category.CreateAt, &category.UpdateAt)
		if err != nil {
			log.Println("GetAllCategory 取值出错:", err)
			return nil, err
		}
		categorys = append(categorys, category)
	}
	return categorys, nil
}

func GetCategoryNameById(id int) string {
	rows := DB.QueryRow("select name from blog_category where cid = ?", id)
	var categoryName string
	_ = rows.Scan(&categoryName)
	return categoryName
}

func PostListByCategoryId(page, pageSize, cid int) []models.Post {
	page = (page - 1) * pageSize
	rows, err := DB.Query("select * from blog_post where category_id	 = ? limit ?,?", cid, page, pageSize)
	if err != nil {
		log.Panicln(err.Error())
		return nil
	}
	var posts []models.Post
	for rows.Next() {
		var post models.Post
		rows.Scan(
			&post.Pid,
			&post.Title,
			&post.Content,
			&post.Markdown,
			&post.CategoryId,
			&post.UserId,
			&post.ViewCount,
			&post.Type,
			&post.Slug,
			&post.CreateAt,
			&post.UpdateAt,
		)
		posts = append(posts, post)
	}
	return posts
}

func PostCountByCategoryId(cid int) (total int) {
	rows := DB.QueryRow("select count(1) from blog_post where category_id = ?", cid)
	err := rows.Scan(&total)
	if err != nil {
		panic(err)
		return 0
	}
	return
}
